#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "qdialogsetsize.h"
#include "qdialoglocate.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    theModel = new QStandardItemModel(this);
    theSelection = new QItemSelectionModel(theModel);
    ui->tableView->setModel(theModel);
    ui->tableView->setSelectionModel(theSelection);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::setActLocateEnable(bool enable)
{
    ui->actTabLocate->setEnabled(enable);
}

void MainWindow::setDialogLocaltNull()
{
    dialogLocate = NULL;
}

void MainWindow::setCellText(int row, int column, QString text)
{
    QModelIndex index  = theModel->index(row, column);
    theModel->setData(index, text, Qt::DisplayRole);
    theSelection->clearSelection();
    theSelection->setCurrentIndex(index, QItemSelectionModel::Select);
}


void MainWindow::on_actTabSetSize_triggered()
{
    QDialogSetSize *dlg = new QDialogSetSize(this);
    dlg->setRowsColumns(theModel->rowCount(), theModel->columnCount());
    int ret = dlg->exec();
    if(ret == QDialog::Accepted)
    {
        int row = dlg->rowCount();
        int column = dlg->columnCount();
        theModel->setColumnCount(column);
        theModel->setRowCount(row);
    }
    delete dlg;
}

void MainWindow::on_actTabLocate_triggered()
{
    //设置非模态
    ui->actTabLocate->setEnabled(false);
    dialogLocate = new QDialogLocate(this);
    dialogLocate->setAttribute(Qt::WA_DeleteOnClose);
    Qt::WindowFlags flags = dialogLocate->windowFlags();
    dialogLocate->setWindowFlags(flags | Qt::WindowStaysOnTopHint);
    //这里设置没有选中某个单元格时的
    dialogLocate->setRange(theModel->rowCount(), theModel->columnCount());
    //获取选中单元格的行列并同步到对话框中
    QModelIndex currentIdx = theSelection->currentIndex();
    if(currentIdx.isValid())
    {
        dialogLocate->setRange(currentIdx.row(), currentIdx.column());
    }
    connect(dialogLocate, &QDialogLocate::changeCellText, this, &MainWindow::setCellText);

    dialogLocate->show();
}

void MainWindow::on_tableView_clicked(const QModelIndex &index)
{
    if(dialogLocate)
    {
        dialogLocate->setValue(index.row(), index.column());
    }
}
